/*
 * @Author: yangzonglong
 * @Date: 2021-02-22 13:46:04
 * @version: v1.0.0
 * @Descripttion: 表单设计
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-06 15:22:59
 * @Auditor:
 */
import React, { useReducer, useMemo, useEffect, useImperativeHandle, forwardRef } from 'react';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import Context from './../context';
import reducer, { initialState } from './../reducer';
import Menu from './components/menu/Menu';
import Main from './components/main/Main';
import Setting from './components/setting/Setting';
import style from './design.module.scss';
import { DesignRefProps, DesignProps, FdReducerProps } from './../interface';
import { createRandomStr } from '../../fd/util';
import './../fd.scss';

export default forwardRef(({ structure, noFormNameDesc, onChange }: DesignProps, ref: React.Ref<DesignRefProps>) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  useImperativeHandle(ref, () => ({
    getData(isExport?: boolean) {
      // if(isExport) {
      //   return { list: state.list?.map(item => ({ ...item, id: item.type === "dataList" ? createRandomStr(item.type) : item.id })), modelListAndModelName: state.modelListAndModelName };
      // }
      return { list: state.list, modelListAndModelName: state.modelListAndModelName };
    },
    changePreview() {
      dispatch({ preview: !state.preview });
    },
    setFormInfo(v) {
      dispatch({ formDesc: v?.formDesc!, formName: v?.formName! });
    },
    sync(list) {
      dispatch({ list, curControl: {} as any });
    },
  }));

  useEffect(() => {
    const list = structure?.list || [];
    dispatch({ list, noFormNameDesc, modelListAndModelName: structure?.modelListAndModelName });
  }, [structure, noFormNameDesc]);

  const store = useMemo(
    () => ({
      state,
      dispatch: (state: FdReducerProps) => {
        dispatch(state);
        onChange?.(state);
      },
    }),
    [state, onChange]
  );

  return (
    <DndProvider backend={HTML5Backend}>
      <Context.Provider value={store}>
        <div className={style.wrap}>
          <Menu />
          <Main />
          {state.curControl?.id && <Setting />}
        </div>
      </Context.Provider>
    </DndProvider>
  );
});
